package com.gitee.ly.ymorm.executor.handler;

import com.gitee.ly.ymorm.executor.Executor;
import com.gitee.ly.ymorm.mapping.BoundSql;
import com.gitee.ly.ymorm.mapping.ParamMap;
import com.gitee.ly.ymorm.mapping.YmOrmStatement;

import java.sql.*;
import java.util.List;

/**
 * CallableStatementHandler
 *
 * @author ly
 **/
public class CallableStatementHandler extends BaseStatementHandler {
    public CallableStatementHandler(Executor executor, YmOrmStatement ymOrmStatement, ParamMap parameterObject, BoundSql boundSql) {
        super(executor, ymOrmStatement, parameterObject, boundSql);
    }

    @Override
    protected Statement instantiateStatement(Connection connection) throws SQLException {
        String sql = boundSql.getSql();
        return connection.prepareCall(sql);
    }

    @Override
    public void batch(Statement statement) throws SQLException {
        CallableStatement cs = (CallableStatement) statement;
        cs.addBatch();
    }

    @Override
    public int update(Statement statement) throws SQLException {
        CallableStatement cs = (CallableStatement) statement;
        cs.execute();
        int rows = cs.getUpdateCount();
        return rows;
    }

    @Override
    public <E> List<E> query(Statement statement, Class<? extends E> resultType) throws SQLException {
        CallableStatement cs = (CallableStatement) statement;
        cs.execute();
        List<E> resultList = resultSetHandler.handleResultSets(cs);
        return resultList;
    }
}
